import time
import json
import hashlib
from math import atan2, degrees, pi, floor


def handler(message):
    amsg = json.loads(message)
    phases = amsg['data']
    server_time = phases[0]['serverTime']
    ts = time.strftime("%Y%m%d", time.localtime(server_time / 1000))
    _chid = phases[0]['chid'] #pubid
    chid = _chid + '::' + ts #pubid::201600110
    num_phases = len(phases)
    total_time = phases[-1]['time']

    # count short series
    print("total_time:", total_time)
    print("num_phases:", num_phases)
    if num_phases < 5 or total_time < 5000:
        print(r"db.action.update_one({'_id': chid}, {'$inc': {'short': 1}}, upsert=True)")
        return True

    # types_set = set([])
    types = []

    for i in range(num_phases):
        aphase = phases[i]
        t = aphase['type']

        # skip click without mousemove
        if (t == 'click') or (t == 'dblclick'):
            withmousemove = False
            for _t in types:
                if _t.startswith('mousemove'):
                    withmousemove = True
            if not withmousemove:
                return True

        # mousemove zone
        if i > 0 and (t == 'mousemove') and (types[-1].startswith('mousemove')):
            frontphase = phases[i - 1]
            delta_y = aphase['y'] - frontphase['y']
            delta_x = aphase['x'] - frontphase['x']
            rads = atan2(-delta_y, delta_x)
            rads %= 2 * pi
            degs = degrees(rads)
            zone = str(int(floor(degs / 45)))
            t += zone

        # keyboard area
        if t == 'keydown' or (t == 'keyup'):
            if (48 <= aphase['key'] <= 57) or (96 <= aphase['key'] <= 105):
                t += '_num'
            elif 65 <= aphase['key'] <= 90:
                t += '_letter'
            else:
                t += '_fn'

        # remove repeated actions
        if i > 0 and t == types[-1]:
            continue

        types.append(t)
        # types_set.add(t)

    print("types len:", len(types), types)
    if len(types) < 5:
        print(r"db.action.update_one({'_id': chid}, {'$inc': {'short': 1}}, upsert=True)")
        return True

    print(r"db.action.update_one({'_id': chid}, {'$inc': {'long': 1}}, upsert=True)")
    hash_value = hashlib.sha1(''.join(types)).hexdigest()
    print(types)
    return True

with open("./onebehavior") as f:
    msg = f.read()
    handler(msg)